package com.yc.damai.web;

import com.yc.damai.entity.User;
import com.yc.damai.util.QRCodeUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@ServerEndpoint("/qc/{uuid}")
@RestController
public class QrcodeDo {

    // 二维码容器
    // private static Map<String,CodeState> qrcodeMap = new HashMap<>();
    // PC端会话容器: UUID : 会话
    private static Map<String, HttpSession> sessionMap = new HashMap<>();

    @RequestMapping(value = "qrcode", produces = MediaType.IMAGE_JPEG_VALUE)
    public void qrcode(String text, OutputStream out) throws Exception {
        QRCodeUtil.encode(text,
                "d:/8d87b5e43a744167831157eef0b9fb21.jpg",
                out, true);
    }

    // PC 端浏览器
    @RequestMapping(value = "loginCode", produces = MediaType.IMAGE_JPEG_VALUE)
    public void qrcodeForLogin(OutputStream out,
                               HttpSession session,
                               HttpServletResponse response) throws Exception {
        // 唯一的二维码 => UUID
        // 访问的地址 + 二维码
        String uuid = UUID.randomUUID().toString();
        String url = "http://192.168.99.100/user/scanCode?qrcode=" + uuid;
        System.out.println("url = " + url);
        // 将二维码保存到容器中, 并且记录状态
        // qrcodeMap.put(uuid, new CodeState());
        // 将会话保存到 会话容器
        sessionMap.put(uuid, session);
        // 创建 Cookie
        Cookie cookie = new Cookie("uuid", uuid);
        // 有效期 1 分钟
        cookie.setMaxAge(60);
        // 设置路径 为更目录
        cookie.setPath("/");
        response.addCookie(cookie);
        qrcode(url,out);
    }

    // 手机扫描访问的地址  ==> 没有手机APP ==> 打开一个手机版的登录页面
    @RequestMapping("scanCode")
    public ModelAndView scanCode(String qrcode, ModelAndView mav){
        mav.setViewName("appLogin.html?qrcode=" + qrcode);
        return mav;
    }

    // 手机端浏览器  qrcode => uuid
    // 修改扫码的状态
    @RequestMapping("modifyCodeState")
    public String modifyCodeState(
            String qrcode, @RequestBody User user) throws IOException {
//        final CodeState codeState = qrcodeMap.get(qrcode);
//        codeState.status = 1;
        // 手机端浏览器向服务器发送用户信息
        System.out.println("user = " + user);
        final HttpSession session = sessionMap.get(qrcode);
        System.out.println("session.getId() = " + session.getId());
        // 将用户对象存入到 PC 端的会话中  => 完成了PC端登录
        session.setAttribute("loginedUser", user);
        // 从 httpSession 中获取 webSocketSession
        Session webSocketSession = (Session) session.getAttribute("WebSocketSession");
        // 通知 PC 端浏览器登录成功!
        webSocketSession.getBasicRemote().sendText("login success!");
        return "OK!";
    }

    // 扫码状态
//    private static class CodeState {
//        int status ;  // 0 未扫码,  1 已扫码
//    }


    //--------------------------------------------------------------------------//
    //  SpringMVC 的控制器 与 WebSocket 对象 是两个独立的对象
    //--------------------------------------------------------------------------//

    // PC 浏览器的 WebSocket
    @OnOpen  //qrcode
    public void onOpen(@PathParam("uuid") String uuid, Session session){
        System.out.println("uuid = " + uuid);
        final HttpSession httpSsession = sessionMap.get(uuid);
        System.out.println("httpSsession.getId() = " + httpSsession.getId());
        // 将 WebSocketSession 保存到  httpSsession
        httpSsession.setAttribute("WebSocketSession",session);
    }

}


